package com.rsscollector.controller.admin.action;

import com.rsscollector.controller.admin.form.CatalogForm;
import com.rsscollector.model.CatalogFacade;
import com.rsscollector.model.vo.Category;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

public class CatalogAction extends Action {


    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

        CatalogForm catalogForm = (CatalogForm) form;

        String action = catalogForm.getAction();
        System.out.println("action="+action);
        if ("Remove".equals(action)) {
            String nodeType = catalogForm.getSelectedNodeId().substring(0, 3);
            Long selectedNodeId = new Long(catalogForm.getSelectedNodeId().substring(3));
            Long parentSelectedNodeId = new Long(catalogForm.getParentSelectedNodeId().substring(3));
            if ("url".equals(nodeType)) {
                CatalogFacade.removeRssUrl(selectedNodeId, parentSelectedNodeId);
            } else {
                CatalogFacade.removeCategory(selectedNodeId);
            }
        } else if ("Create Category".equals(action) && !"url".equals(catalogForm.getSelectedNodeId().substring(0, 3))) {
            Long selectedNodeId = new Long(catalogForm.getSelectedNodeId().substring(3));
            CatalogFacade.createCategory(catalogForm.getNewCategory(), catalogForm.getNewTitle(), selectedNodeId);
        } else if ("Update Category".equals(action)) {
            List listCate = CatalogFacade.getRootCategories(true);
            if (listCate != null && listCate.size() > 0) {
                for (int i = 0; i < listCate.size(); i++) {
                    Category obj = (Category) listCate.get(i);
                    String catName = request.getParameter("newCategory"+i);
                    String catTitle = request.getParameter("newTitle"+i);
                    System.out.println("name-title="+catName+"-"+catTitle);
                    obj.setName(catName);
                    obj.setTitle(catTitle);
                }
            }
            Long selectedNodeId = new Long(catalogForm.getSelectedNodeId().substring(3));
            CatalogFacade.createCategory(catalogForm.getNewCategory(), catalogForm.getNewTitle(), selectedNodeId);
        } else if ("Create URL".equals(action)) {
            Long selectedNodeId = new Long(catalogForm.getSelectedNodeId().substring(3));
            CatalogFacade.createRssUrl(catalogForm.getNewUrl(), selectedNodeId, catalogForm.getNewUrlProvider());
        }

        return mapping.findForward("success");
    }

}
